//
//  YJUserAccountViewModel.swift
//  YJWeiBo
//
//  Created by Jim1024 on 2017/1/12.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import UIKit
import Alamofire

class YJUserAccountViewModel: NSObject {
    
    override init() {
        super.init()
        
        userAccount = loadUserAccount()
    }
    
    // 单例
    static let sharedInstance: YJUserAccountViewModel = YJUserAccountViewModel()
    
    var userAccount: YJUserAccount?
    private let accountPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! + "/account.plist"
    var userLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    /// 获取AccessToken
    func loadAccessToken(code: String, completion: @escaping (_ error: NSError?) -> ()) {
        // 获取accessToken的url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 拼接参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        Alamofire.request(urlString, method: .post, parameters: parameters).responseJSON { (response) in
            guard let result = response.result.value else {
                completion(response.result.error as NSError?)
                return
            }
            self.userAccount = YJUserAccount(result as! [String : Any])
            JPrint("userAccount: \(self.userAccount)")
            self.saveUserAccount()
            completion(nil)
        }
    }
    
    /// 获取用户信息
    func loadUserInfo(completion: @escaping (_ error: NSError?) -> ()) {
        // url
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 参数
        let parameters: [String : AnyObject] = ["uid" : userAccount!.uid! as AnyObject]
        
        YJNetworkManager.request(urlStrig: urlString, parameters: parameters) { (result, error) in
            if error != nil {
                completion(error)
                return
            }
            
            self.userAccount?.screen_name = result?["screen_name"] as? String
            self.userAccount?.avatar_large = result?["avatar_large"] as? String
            
            self.saveUserAccount()
            completion(nil)
        }
    }
    
    /// 保存模型到沙盒
    private func saveUserAccount() {
        if userAccount != nil {
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }
    }
    
    
    private func loadUserAccount() -> YJUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as? YJUserAccount
        
        if userAccount != nil && userAccount?.expiresDate?.compare(Date()) == ComparisonResult.orderedDescending {
            return userAccount
        }
        return nil
    }
}
